//------------------------------------------------------------------------------
//  <copyright file="InterpolationConsumerProducerAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  </copyright>
//------------------------------------------------------------------------------

namespace Microsoft.Robotics.Runtime
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.Threading;

    /// <summary>
    /// A consumer/producer that subscribes to two agents and interpolates the incoming message based at time stamps specified by timer
    /// Interpolation relies on an AgentMessage property called OriginatingTime. 
    /// This property represents the time when the hardware generated the data (e.g. Kinect depth frame) and needs to be carried from agent message to agent message through the pipeline, 
    /// e.g. the GyroscopeMessage should be interpolated to the same originating time as the underlying Kinect frame.
    /// </summary>
    /// <typeparam name="TMessage">The first type of input messages accepted by the consumer part of the agent.</typeparam>
    /// <typeparam name="TTimer">The second type of input messages accepted by the consumer part of the agent.</typeparam>
    [DataContract]
    public abstract class InterpolationConsumerProducerAgent<TMessage, TTimer> : ProducerAgent<TMessage>, ISubscriptionReceiver<InterpolationMessage<TMessage>>
        where TMessage : AgentMessage
        where TTimer : AgentMessage
    {
        /// <summary>
        /// The agent we subscribe to.
        /// </summary>
        private IAgentHost interpolationAgent;

        /// <summary>
        /// Initializes a new instance of the InterpolationConsumerProducerAgent class.
        /// This constructor is not called when the agent is created from a manifest file.
        /// </summary>
        /// <param name="name">A friendly name for this agent instance.</param>
        public InterpolationConsumerProducerAgent(string name)
            : base(name)
        {
        }

        /// <summary>
        /// Gets the name of the first producer. Needs to be provided by derived classes.
        /// </summary>
        protected abstract string ProducerName1
        {
            get;
        }

        /// <summary>
        /// Gets the name of the second producer. Needs to be provided by derived classes.
        /// </summary>
        protected abstract string ProducerName2
        {
            get;
        }

        /// <summary>
        /// Called after construction, to allow the agent to finish initialization. 
        /// </summary>
        /// <param name="locator">A locator that can be used to find other agents.</param>
        public override void Initialize(AgentLocator locator)
        {
            Agent.ValidateParameter(string.IsNullOrEmpty(this.ProducerName1), this.ProducerName1, "KinectAgent");
            Agent.ValidateParameter(string.IsNullOrEmpty(this.ProducerName2), this.ProducerName2, "JointMessageAgent");

            base.Initialize(locator);

            // create the join agent and add it to the agent pipeline, then subscribe to it.
            string syncName = string.Format("Interp_{0}<{1}, {2}>", this.Name, this.ProducerName1, this.ProducerName2);
            InterpolationAgent<TMessage, TTimer> interpolAgent = new InterpolationAgent<TMessage, TTimer>(syncName, this.ProducerName1, this.ProducerName2);
            this.interpolationAgent = locator.Register(interpolAgent);
            this.interpolationAgent.Subscribe(this);
        }

        /// <summary>
        /// Called when the agent transitions from inactive to active.
        /// </summary>
        public override void OnActivated()
        {
            this.interpolationAgent.Activate();
            base.OnActivated();
        }

        /// <summary>
        /// Called when the agent transitions from active to inactive.
        /// </summary>
        public override void OnDeactivated()
        {
            this.interpolationAgent.Deactivate();
            base.OnDeactivated();
        }

        /// <summary>
        /// Called when a new input message is available, in this case a combined message containing two synced messages.
        /// </summary>
        /// <param name="message">The combined message to receive.</param>
        public void Receive(InterpolationMessage<TMessage> message)
        {
            this.Receive(message.StartValue, message.EndValue, message.OriginatingTime);
        }

        /// <summary>
        /// Called to interpolate between the start and end messages by the time provided by the interpolation time.        
        /// </summary>
        /// <param name="start">The start message to interpolate</param>
        /// <param name="end">The end message to interpolate</param>
        /// <param name="interpolationTme">The time for interpolation</param>
        protected abstract void Receive(TMessage start, TMessage end, long interpolationTme);
    }
}
